<%@ page language="java" contentType="text/html; charset=UTF-8" import="java.util.*,
com.brother.model.*,com.ibatis.common.util.*,org.json.JSONObject"   pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ include file="international.jsp" %> 
<jsp:useBean id="trackerService" class="com.brother.service.TrackerService"></jsp:useBean>
<%
String action = request.getParameter("action");
String userName = request.getParameter("userName");
String trackerName = request.getParameter("trackerName");
String userTrackerId = request.getParameter("userTrackerId");
int start = Integer.parseInt(request.getParameter("start")==null?"0":request.getParameter("start"));
int limit = Integer.parseInt(request.getParameter("limit")==null?"20":request.getParameter("limit"));

if(userName != null && userName.startsWith("Select")){
	userName = null;
}
if(trackerName != null && trackerName.startsWith("Select")){
	trackerName = null;
}
if(userTrackerId != null && userTrackerId.startsWith("Select")){
	userTrackerId = null;
}

if(action != null && action.equalsIgnoreCase("del")){
	String[] trackerids = request.getParameterValues("trackerid");
	for(String trackerid: trackerids)
	trackerService.deleteTracker(trackerid);
	response.sendRedirect("trackerList.jsp");
	return;
}
com.brother.model.Customer c = (com.brother.model.Customer)session.getAttribute(com.brother.Constants.LOGIN_SESSTION_NAME);
List<Tracker> trackers =new ArrayList();

if(c != null){
	if(action != null && action.equalsIgnoreCase("search")){
		
		if(action.equalsIgnoreCase("page")){
			userName = (String)session.getAttribute("userName");
			trackerName = (String)session.getAttribute("trackerName");
			userTrackerId = (String)session.getAttribute("userTrackerId");
		}else{
			session.setAttribute("userName", userName);
			session.setAttribute("trackerName", trackerName);
			session.setAttribute("userTrackerId", userTrackerId);			
		}
		
	}
}else{
	return;
}
trackers = trackerService.findChildrenTracker(c.getUserid(), userName, trackerName, userTrackerId);
PaginatedArrayList pageData = new PaginatedArrayList(trackers, 20);




String pageNo = request.getParameter("pageNo");
if(pageNo == null || !pageNo.matches("^\\d*$")){
	pageNo = "0";
}

pageData.gotoPage(start/limit);

Iterator<Tracker> datas = pageData.iterator();

int totalSize = trackers.size();
int totalPages = (totalSize % pageData.getPageSize() ==0) ?  (totalSize / pageData.getPageSize()): (totalSize / pageData.getPageSize()+ 1);

%>
					  
{"totalCount":"<%=totalSize %>","models":[
<%
int count = 0;

while(datas.hasNext()){
	Tracker tracker = datas.next();	
	count++;
	JSONObject json = new JSONObject(tracker); 
	out.print(json.toString());
%>


 
<%if(datas.hasNext()){ %>,<%} %><%} %>]}
					  
<%
com.brother.database.DataBase.closeThreadConnection();
%>